package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.constans.ResultCode;
import com.qf.dto.R;
import com.qf.exceptions.AddDataException;
import com.qf.mapper.AuthorsMapper;
import com.qf.mapper.CategoriesMapper;
import com.qf.pojo.Authors;
import com.qf.pojo.Books;
import com.qf.pojo.Categories;
import com.qf.service.IBooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BooksController {
    private AuthorsMapper authorsMapper;
    private CategoriesMapper categoriesMapper;
@Autowired
    public void setCategoriesMapper(CategoriesMapper categoriesMapper) {
        this.categoriesMapper = categoriesMapper;
    }
@Autowired
    public void setAuthorsMapper(AuthorsMapper authorsMapper) {
        this.authorsMapper = authorsMapper;
    }

    private IBooksService booksService;
    @Autowired
    public void setBooksService(IBooksService booksService) {
        this.booksService = booksService;
    }
    @GetMapping("/books")
    public R findAllBooks(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "3") int limit){
        PageInfo<Books> booksPageInfo = booksService.findAll(page, limit);
        return R.setOk(booksPageInfo);
    }
    @PostMapping("/newbook")
    public R addBooks(@RequestBody Books books){
        System.out.println("添加的ID"+books.getAuthorid());
        System.out.println("添加书哈哈");
        if(books==null||books.isNull()){
            throw new AddDataException("数据不完整", ResultCode.NULL_DATA);
        }
        Authors authors = authorsMapper.find(books.getAuthorid());
        Categories categories = categoriesMapper.findById(books.getCategoryid());
        if(authors==null&&categories==null){
            throw new AddDataException("作者不存在或分类不存在", ResultCode.NULL_DATA);
        }
        booksService.addBooks(books);
        return  R.setOk(null);
    }

}
